import { useState, useEffect } from 'react'
import { Tree, Button, message } from 'antd'
import type { TreeDataNode, TreeProps } from 'antd';
import {  UpdatePermission, PermList } from '../../../service/index-roleList'

// 角色分配数据类型
interface MenuData {
  children?: MenuData[]
  createTime: number
  disabled: boolean
  isBtn: boolean
  name: string
  path: string
  pid: string
  __v: number
  _id: string
}

interface propos {
  characterPermission: string[];
  onClose: () => void;
  characterId: string;
}

const PermissionTree = ({ characterPermission, onClose, characterId }: propos) => {

  const [TreeData, setTreeData] = useState<MenuData[]>([]); // 角色分配树状图数据
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]); // 选中的权限

  // 树状图
  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
    // console.log('onCheck', checkedKeys, info);
    setCheckedKeys(checkedKeys as string[])
  };


  // 角色分配数据结构函数
  const gettreeData = (data: MenuData[]) => {
    const arr: TreeDataNode[] = data.map((item: MenuData) => {
      return {
        title: item.name,
        key: item._id,
        children: item.children ? gettreeData(item.children) : [],
      }
    });
    return arr;
  }
  
  // 树状图数据
  const treeData: TreeDataNode[] = gettreeData(TreeData)

  useEffect(() => {

    PermList()
      .then(res => {
        console.log(res.data.data.list)
        setTreeData(res.data.data.list)
      })
      .catch(err => console.log(err))


    // 选中的权限
    setCheckedKeys(characterPermission)
  }, [characterPermission])

  return (
    <>
      <Tree
        checkable
        onSelect={onSelect}
        onCheck={onCheck}
        treeData={treeData}
        checkedKeys={checkedKeys}
      />
      <Button type="primary" onClick={() => {
        onClose();
        // 更新角色权限
        console.log(checkedKeys)
        UpdatePermission(characterId, checkedKeys)
         .then(res => {
            console.log('更新角色权限成功')
            message.success('更新角色权限成功')
          })
         .catch(err => console.log(err))
      }}>确定</Button>
    </>
  )
}

export default PermissionTree